<template>
  <div
    class="comments"
    :class="isShowBox1 ? 'art-cmt-container-1' : 'art-cmt-container-2'"
  >
    <van-sticky offset-top="11.73333vw">
      <div class="title van-hairline--bottom">
        <span>全部评论 ({{ total }})</span>
        <span>{{ teacher.like_count }} 点赞</span>
      </div>
    </van-sticky>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="initComments"
    >
      <div v-for="comment in comments" :key="comment.id" class="single-com">
        <CommentItem :comment="comment"></CommentItem>
      </div>
    </van-list>

    <!-- 底部添加评论区域 - 1 -->
    <div class="add-cmt-box van-hairline--top" v-if="isShowBox1">
      <van-icon name="arrow-left" size="18" @click="$router.back()" />
      <div class="ipt-cmt-div" @click="showBox2">发表评论</div>
      <div class="icon-box">
        <van-badge :content="total" :max="99">
          <van-icon
            name="comment-o"
            size="20"
            @click="$emit('click-comment')"
          />
        </van-badge>
        <van-icon
          name="star"
          size="20"
          color="#fbd326"
          v-if="is_following"
          @click="unfollowTeacher"
        />
        <van-icon name="star-o" size="20" v-else @click="followTeacher" />
        <van-icon
          name="like"
          size="20"
          v-if="is_liking"
          color="red"
          @click="dislikeTeacher"
        />
        <van-icon name="like-o" size="20" v-else @click="likeTeacher" />

        <van-icon name="chat" size="20" color="#fbd326" @click="goChat()" />
      </div>
    </div>

    <!-- 底部添加评论区域 - 2 -->
    <div class="cmt-box van-hairline--top" v-else>
      <div class="left">
        <van-row type="flex">
          <van-col><span>评分:</span></van-col>
          <van-col
            ><van-rate v-model="rating" class="rat" ref="rat" touchable
          /></van-col>
        </van-row>
        <textarea
          placeholder="友善评论、理性发言、阳光心灵"
          @blur="hideBox2"
          ref="iptCmt"
          v-model.trim="cmt"
        ></textarea>
      </div>
      <van-button
        type="default"
        :disabled="cmt.length == 0 || rating == 0"
        @click="pubCmt"
        >发布</van-button
      >
    </div>
  </div>
</template>

<script>
import CommentItem from "@/components/Home/CommentItem";
import {
  pubCommentAPI,
  commentListAPI,
  likeTeacherAPI,
  dislikeTeacherAPI,
  followTeacherAPI,
  unfollowTeacherAPI,
} from "@/api/userApi";
import { mapState } from "vuex";
export default {
  components: {
    CommentItem,
  },
  props: ["teacher"],
  computed: {
    ...mapState("user", ["tokenInfo", "profile"]),
    is_liking() {
      return this.teacher.like_users?.includes(this.profile.id);
    },
    is_following() {
      return this.teacher.fans?.includes(this.profile.id);
    },
  },
  data() {
    return {
      // 用户填写的评论内容
      cmt: "",
      rating: 0,
      page: 1,
      comments: [],
      loading: false,
      finished: false,
      // 是否展示评论区域1（如果值为 true 则展示评论区域1；如果值为 false 则展示评论区域2）
      isShowBox1: true,
      total: 0,
    };
  },
  methods: {
    showBox2() {
      this.isShowBox1 = false;
      // 1. 将回调函数延迟到下次 DOM 更新完毕之后执行
      this.$nextTick(() => {
        // 2. 通过 ref 获取到 textarea 的引用
        this.$refs.iptCmt.focus();
      });
    },
    hideBox2(e) {
      if (e.relatedTarget && e.relatedTarget.className == "van-rate__item") {
        this.$nextTick(() => {
          // 2. 通过 ref 获取到 textarea 的引用
          this.$refs.iptCmt.focus();
        });
        return;
      }
      setTimeout(() => {
        // 隐藏第二个评论区域
        this.isShowBox1 = true;
        // 清空用户输入的评论内容
        this.cmt = "";
        this.rating = 0;
      }, 100);
    },
    // 点击了发布评论的按钮
    async pubCmt() {
      const comment = {
        user_id: this.tokenInfo.user_id,
        rating: this.rating,
        content: this.cmt,
        teacher_id: this.teacher.id,
      };
      const { data: res } = await pubCommentAPI(comment);
      if (res.message) {
        this.$notify({
          type: "warning",
          message: "评论失败",
          duration: 2000,
        });
        return;
      }
      this.comments.unshift(res);
      this.total++;
    },
    async initComments() {
      const { data: res } = await commentListAPI(
        this.$route.params.id,
        this.page
      );
      this.total = res.count;
      if (!res.next) {
        this.finished = true;
      }
      this.comments = [...this.comments, ...res.results];
      this.page++;
      this.loading = false;
    },
    async likeTeacher() {
      const { data: res } = await likeTeacherAPI(this.teacher.id);
      if (res.message == "OK") {
        this.$emit("reload");
        this.$notify({
          type: "success",
          message: "点赞成功",
          duration: 1000,
        });
      }
    },
    async dislikeTeacher() {
      const { data: res } = await dislikeTeacherAPI(this.teacher.id);
      if (res.message == "OK") {
        this.$emit("reload");
        this.$notify({
          type: "success",
          message: "取消点赞成功",
          duration: 1000,
        });
      }
    },
    async followTeacher() {
      const { data: res } = await followTeacherAPI(this.teacher.id);
      if (res.message == "OK") {
        this.$emit("reload");
        this.$notify({
          type: "success",
          message: "关注成功",
          duration: 1000,
        });
      }
    },
    async unfollowTeacher() {
      const { data: res } = await unfollowTeacherAPI(this.teacher.id);
      if (res.message == "OK") {
        this.$emit("reload");
        this.$notify({
          type: "success",
          message: "取消关注成功",
          duration: 1000,
        });
      }
    },
    goChat() {
      this.$router.push(`/chat/${this.teacher.user_id}`);
    },
  },
};
</script>

<style lang="less" scoped>
.comments {
  .title {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
    background: #fff;
    font-size: 16px;
    span {
      font-size: 16px;
      &:last-child {
        color: #ccc;
        font-size: 14px;
      }
    }
  }
}

// 外层容器
.art-cmt-container-1 {
  padding-bottom: 46px;
}
.art-cmt-container-2 {
  padding-bottom: 80px;
}

// 发布评论的盒子 - 1
.add-cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 46px;
  line-height: 46px;
  padding-left: 10px;
  .ipt-cmt-div {
    flex: 1;
    border: 1px solid #efefef;
    border-radius: 15px;
    height: 30px;
    font-size: 12px;
    line-height: 30px;
    padding-left: 15px;
    margin-left: 10px;
    background-color: #f8f8f8;
  }
  .icon-box {
    width: 40%;
    display: flex;
    justify-content: space-evenly;
    line-height: 0;
  }
}

.child {
  width: 20px;
  height: 20px;
  background: #f2f3f5;
}

// 发布评论的盒子 - 2
.cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  padding-left: 10px;
  box-sizing: border-box;
  background-color: white;
  .left {
    height: 70%;
    flex: 1;
    textarea {
      width: 80%;
      display: block;
      height: 50%;
      border: 1px solid #efefef;
      background-color: #f8f8f8;
      resize: none;
      border-radius: 6px;
      padding: 5px;
    }
  }
  .van-button {
    height: 80%;
    margin-right: 10px;
    border: none;
    background-color: #3a88f9;
    color: #fff;
  }
}
</style>
